/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.extraty.question483;

/**
 * @author Created by Neil Wang
 * @version 1.0.0
 * @date 2021/9/7 1:22 下午
 */
public class Solution1 {
    public String smallestGoodBase(String n) {
        final int mustTrueNumber = 2;
        long number = Long.parseLong(n);
        for (int len = getMaxLen(number); len >= mustTrueNumber + 1; len--) {
            long numberSystem = assertNumberSystem(number, len);
            if (verifyResult(len, numberSystem, number)) return String.valueOf(numberSystem);
        }
        return String.valueOf(number - 1);
    }

    private boolean verifyResult(int len, long numberSystem, long number) {
        long res = 0;
        for (int i = 0; i < len; i++) res = res * numberSystem + 1;
        return res == number;
    }

    private long assertNumberSystem(long m, int len) {
        return (long) Math.pow(m, 1.0 / (len - 1));
    }

    private int getMaxLen(long m) {
        return (int) (Math.log(m) / Math.log(2) + 1);
    }
}
